
/**
 * 地图
 */
let mapUtil = {};
let baiduKey="QG5Qx9IVsGq0Xqu55RT3BcgUEztORTX9";
/**
 * 加载百度地图
 */
mapUtil.loadBaiduMap=function(id,loadDraw){
  return new Promise(function(resolve, reject) {
    let mapInfo = new Object();
    window.onBMapCallback = function() {
      if (typeof BMapGL !== 'undefined') {
        var map = new BMapGL.Map(id);
        if(!loadDraw){
          mapUtil.loadBaiduDrawTool(map).then((drawingManager)=>{
            mapInfo.drawingManager=drawingManager;
            mapInfo.map = map;
            resolve(mapInfo);
          });
        }else{
          mapInfo.map = map;
          resolve(mapInfo);
        }
      }
      if ( typeof BMap !== 'undefined') {
        var map = new BMap.Map(id);
        if(!loadDraw){
          mapUtil.loadBaiduDrawTool(map).then((drawingManager)=>{
            mapInfo.drawingManager=drawingManager;
            mapInfo.map = map;
            resolve(mapInfo);
          });
        }else{
          mapInfo.map = map;
          resolve(mapInfo);
        }
      }
    }
    let script = document.createElement('script')
    script.type = 'text/javascript'
    //  script.src ='https://api.map.baidu.com/api?v=1.0&type=webgl&ak=' + baiduKey + '&callback=onBMapCallback'
     script.src ='http://api.map.baidu.com/api?v=3.0&ak=' + baiduKey + '&callback=onBMapCallback';
    script.onload=function(){
    }
    script.onerror = reject;
    document.head.appendChild(script)
  })
},

mapUtil.getStyle=function(){
  var styleOptions = {
    strokeColor:"red",    //边线颜色。
    fillColor:"red",      //填充颜色。当参数为空时，圆形将没有填充效果。
    strokeWeight: 3,       //边线的宽度，以像素为单位。
    strokeOpacity: 0.8,    //边线透明度，取值范围0 - 1。
    fillOpacity: 0.6,      //填充的透明度，取值范围0 - 1。
    strokeStyle: 'solid' //边线的样式，solid或dashed。
   }
   return styleOptions;
}

/**
 * 加载百度地图绘制工具
 * @param  map 
 */
mapUtil.loadBaiduDrawTool=function(map){
    let script = document.createElement('script')
    script.type = 'text/javascript'
    // script.src ='http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js';
   script.src ='./DrawingManager.js';
    document.head.appendChild(script);
    var link = document.createElement('link');
    link.href = "http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css";
    // link.href  ='./DrawingManager_min.css';
    link.rel = 'stylesheet';
    link.type = 'text/css';
    document.head.appendChild(link);
    return new Promise(function(resolve, reject) {
      script.onload=function(){
        var styleOptions = mapUtil.getStyle();
          //实例化鼠标绘制工具
          var drawingManager = new BMapLib.DrawingManager(map, {
            isOpen: false, //是否开启绘制模式
            enableDrawingTool: true, //是否显示工具栏
            drawingToolOptions: {
                anchor: BMAP_ANCHOR_TOP_LEFT, //位置
                offset: new BMap.Size(5, 5), //偏离值
            },
            circleOptions: styleOptions, //圆的样式
            polylineOptions: styleOptions, //线的样式
            polygonOptions: styleOptions, //多边形的样式
            rectangleOptions: styleOptions //矩形的样式
          }); 
          resolve(drawingManager);
      }
    });
}

/**
 * 百度地图搜索空间
 * @param {} map 
 */
mapUtil.loadBaiduSearch=function(map){
  function ZoomControl(){    
    this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;    
    this.defaultOffset = new BMap.Size(10, 10);    
  }    
  // 通过JavaScript的prototype属性继承于BMap.Control   
  ZoomControl.prototype = new BMap.Control();
  ZoomControl.prototype.initialize = function(map){    
     var div = document.createElement("div");
    var form = div.appendChild(document.createElement("form"));
    var input0 = div.appendChild(document.createElement("input"));
    input0.setAttribute("id", "text");
    var input1 = div.appendChild(document.createElement("input"));
    input1.type = "submit";
    input1.value = "定位";
    input1.setAttribute("id", "search")
    // 设置样式  
    div.style.cursor = "pointer";
    div.style.border = "0px solid gray";
    div.style.backgroundColor = "white";
    input0.style.height="20px";
    input1.style.height="20px";
    input1.onclick = function() {
        var name=document.getElementById("text").value;
        var myGeo = new BMap.Geocoder();
	    // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint(name, function(point){
            if (point) {
                  map.centerAndZoom(point, 16);
                  map.addOverlay(new BMap.Marker(point));
            }else{
                  alert("您选择地址没有解析到结果!");
            }
          }, "");
        }
    map.getContainer().appendChild(div);
    return div;
  }
  return  new ZoomControl();
}



/**
 *  获取百度地图预览图
 * @param {中心点} point 
 * @param {*} overlaies 
 * @param {*} width 
 * @param {*} height 
 */
mapUtil.getPreImage=function(map,obj){
  let w = 300;
  let h=  300;
  let z=map.getZoom()-2;
  let point = map.getCenter();
  let paths="";
  let maxlng=point.lng;
  let maxlat=point.lat;
  let minlng=point.lng;
  let minlat=point.lat;
  let overlaies = map.getOverlays();
  if(overlaies!=null && overlaies.length>0){
      for(var i=0;i<overlaies.length>0;i++){
        let arr = overlaies[i].la;
        let temp = "";
        if(arr && arr.length>0){
          for(var j=0;j<arr.length;j++){
            let item = arr[j];
            temp+=";"+item.lng+","+item.lat;
            if(item.lng>maxlng){
              maxlng=item.lng
            }
            if(item.lng<minlng){
              minlng=item.lng
            }
            if(item.lat>maxlat){
              maxlat=item.lat;
            }
            if(item.lat<minlat){
              minlat=item.lat;
            }
          }
        }
        if(temp.length>0){
          paths+="|"+temp.substring(1);
        }
      }
  }
  let centerlng = (maxlng+minlng)/2;
  let centerlat = (maxlat+minlat)/2;
  if(paths.length>0){
    paths=paths.substring(1);
  }
  obj.center=centerlng+','+centerlat;
  obj.points = paths;
  let url = 'http://api.map.baidu.com/staticimage/v2?ak='+baiduKey+'&center='+centerlng+','+centerlat+'&width='+w+'&height='+h+'&zoom='+z+'&maptype=BMAP_EARTH_MAP&pathStyles=0xff0000,5,0.9,0xffffff'+'&paths='+paths;
  return url
}

/**
 * 解析overlay
 * @param {*} map 
 */
mapUtil.parseOverlay=function(map){
  let overlaies = map.getOverlays();
  let result =new Array();
  if(overlaies!=null && overlaies.length>0){
      for(var i=0;i<overlaies.length>0;i++){
        let item = overlaies[i];
        var temp ={};
       
        //如果是圆
        if(item instanceof BMap.Circle){
          temp.type="Circle";
          temp.center=item.point;
          temp.radius=item.getRadius();
          result.push(temp);
        }
        //如果是画线
        else if(item instanceof BMap.Polyline){
          temp.type="Polyline";
          temp.points=item.getPath();
          result.push(temp);
        }
         //如果是多边形
        else  if(item instanceof BMap.Polygon){
          temp.type="Polygon";
          temp.points=item.getPath();
          result.push(temp);
        }
        //  //如果是点
        //  else if(item instanceof BMap.Marker){
        //   temp.type="Marker";
        //   temp.options=item.point;
        //   result.push(temp);
        // }
       
      }
  }
  return result;
}

/**
 * 
 * @param {*} map 
 * @param {*} overlay 
 */
mapUtil.setOverlay=function(map,overlay){
  let result = new Array();
  if(overlay!=null && overlay.length>0){
      let options= mapUtil.getStyle();
      for(var i=0;i<overlay.length>0;i++){
        let item = overlay[i];
        //如果是圆
        if(item.type=="Circle"){
          let centerPoint = new BMap.Point(item.center.lng,item.center.lat);
          let circle = new BMap.Circle(centerPoint,item.radius,options);
          map.addOverlay(circle);
          result.push(circle);
        }
        //如果是画线
        else if(item.type=="Polyline"){
          let line = new BMap.Polyline(item.points,options);
          map.addOverlay(line);
          result.push(line);
        }
         //如果是多边形
        else  if(item.type=="Polygon"){
          let pol = new BMap.Polygon(item.points,options);
          map.addOverlay(pol);
          result.push(pol);
        }
        //  //如果是点
        //  else if(item instanceof BMap.Marker){
        //   temp.type="Marker";
        //   temp.options=item.point;
        //   result.push(temp);
        // }
      }
  }
  return result;
}

export default mapUtil;
